<template>
  <div class="bei">
    <div class="table">
      <div class="top">
        <div class="inpx">
          <div>
            学生姓名：
            <el-input
              v-model="searchDate.stuName"
              size="small"
              placeholder="输入搜索名字"
              class="inp"
            />
          </div>
          <div>
            市场部：<el-select size="small" placeholder="请选择市场部" v-model="searchDate.origin">
              <el-option
                v-for="item in options1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div>
            学院：<el-select size="small" placeholder="请选择学院" v-model="searchDate.collegeId">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            /></el-select>
          </div>
          <div>
            工作城市：<el-cascader
              placeholder="请选择"
              v-model="searchDate.workCity"
              :options="optionscity"
              @change="handleChange"
            />
          </div>
          <el-button type="primary" @click="sousuo">搜索</el-button>
        </div>
        <div class="btn">
          <el-button type="primary" @click="add()">新增毕业学生</el-button>
          <el-button type="primary" @click="delall">批量删除</el-button>
          <el-button
            type="primary"
            @click="dialogTableVisible = true"
            :style="{ marginRight: '20px' }"
            >学生批量导入</el-button
          >
          <!-- 上传upload -->
          <el-dialog v-model="dialogTableVisible" title="学生批量导入" width="800">
            <el-upload class="upload-demo" drag action="#" :http-request="handlestudent" multiple>
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">拖拽上传 <em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip">仅允许导入xls,xlsx个事文件</div>
              </template>
            </el-upload>
            <template #footer>
              <el-button type="primary" @click="confirm">确认</el-button>
              <el-button @click="dialogTableVisible == false">取消</el-button>
            </template>
          </el-dialog>
          <!-- 上传upload -->
          <el-button type="primary" @click="handleExport" style="">学生批量导出</el-button>
        </div>
      </div>
      <!-- 查看详情 -->
      <el-dialog v-model="dialogFormVisible1" title="查看信息" width="500">
        <div :style="{ margin: '10px' }">
          <el-text class="mx">姓名：{{ chadata.stuName }}</el-text>
        </div>
        <div :style="{ margin: '10px' }">
          <el-text class="mx">学号：{{ chadata.stuNo }}</el-text>
        </div>
        <div :style="{ margin: '10px' }">
          <el-text class="mx">班级：{{ chadata.className }}</el-text>
        </div>
        <div :style="{ margin: '10px' }">
          <el-text class="mx">地区：{{ chadata.origin }}</el-text>
        </div>
        <div :style="{ margin: '10px' }">
          <el-text class="mx">时间：{{ chadata.createdTime }}</el-text>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible1 = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 表格 -->
      <div>
        <el-table :data="tableData" style="width: 100%" @selection-change="xuan" ref="selection">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column property="id" label="ID" />
          <el-table-column property="className" label="班级" />
          <el-table-column property="stuName" label="姓名" />
          <el-table-column property="collegeName" label="学院" />
          <el-table-column property="origin" label="市场部" />
          <el-table-column property="status" label="状态" />
          <el-table-column property="workCity" label="城市" />
          <el-table-column align="center">
            <template #header>
              <span>操作</span>
            </template>
            <template #default="scope">
              <el-button type="primary" size="small" @click="cha(scope.row)">查看</el-button>
              <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
                编辑
              </el-button>
              <el-popconfirm
                confirm-button-text="Yes"
                cancel-button-text="No"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="确认删除吗?"
                @confirm="confirmEvent(scope.$index, scope.row)"
                @cancel="cancelEvent"
              >
                <template #reference>
                  <el-button size="small" type="danger"> 删除 </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="fenye">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="pageSize"
          :current-page="currentPage"
          :total="totalItems"
          @current-change="handlePageChange"
        />
      </div>
      <!-- 新增弹框 -->
      <el-dialog v-model="dialogFormVisible" :title="flag ? '新增' : '编辑'" width="500">
        <el-form :model="form">
          <el-form-item label="ID" :label-width="formLabelWidth" v-if="flag == false">
            <el-input v-model="form.id" autocomplete="off" :disabled="flag === false" />
          </el-form-item>
          <el-form-item label="学号" :label-width="formLabelWidth">
            <el-input v-model="form.stuNo" autocomplete="off" />
          </el-form-item>
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="form.stuName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="班级" :label-width="formLabelWidth">
            <el-input v-model="form.className" autocomplete="off" />
          </el-form-item>
          <el-form-item label="状态" :label-width="formLabelWidth">
            <el-input
              v-model="form.status"
              autocomplete="off"
              placeholder="请输入数字，1：未毕业，2：返校重听，3：已就业,4:返回未就业,5:以往未就业"
            />
          </el-form-item>
          <el-form-item label="学院" :label-width="formLabelWidth">
            <el-input
              v-model="form.collegeid"
              autocomplete="off"
              placeholder="请输入数字，1：游戏学院，2：网站工程学院"
            />
          </el-form-item>
          <el-form-item label="城市" :label-width="formLabelWidth">
            <el-input v-model="form.workCity" autocomplete="off" />
          </el-form-item>
          <el-form-item label="来源" :label-width="formLabelWidth">
            <el-input v-model="form.origin" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submit"> 提交 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed, reactive, watch } from 'vue'
import { ElTable } from 'element-plus'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import qs from 'qs'
import { getlist, addlist, edilist, dellist, detaillist, studenimport } from '../../request/index'
import CityData from '../../components/CityData.json'
import { UploadFilled } from '@element-plus/icons-vue'
//总条数
const totalItems = ref(0)
//当前页
const currentPage = ref(1)
//一页几条
const pageSize = ref(10)
////总数量  数据
const tableData = ref([])

//多选  得到表格的ref
const selection = ref(false) //也可以直接传val
//批量导入
const dialogTableVisible = ref(false)
//删除数据
const deldata = ref([])
//查看
const dialogFormVisible1 = ref(false)
const chadata = ref({})
//新增
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
//
//搜索的数据
const searchDate = reactive({
  stuName: '',
  origin: '',
  collegeId: '',
  workCity: '',
  page: 1,
  limit: 10
})
//计算属性得到最后一个城市码
const lastWorkCityValue = computed(() => {
  const workCity = searchDate.workCity
  return workCity.length ? workCity[workCity.length - 1] : ''
})
//是编辑还是新增
const flag = ref(true)
//新增表单
const form = reactive({
  //
  id: '',
  //学号
  stuNo: '',
  //姓名
  className: '',
  //班级
  stuName: '',
  //状态
  status: '',
  //生源地
  origin: '',
  //学院id
  collegeid: '',
  // 城市
  workCity: ''
})
//批量删除
const delall = () => {
  let ids = deldata.value
  dellist(ids).then((res) => {
    // console.log(res, '批量删除成功')
    ElMessage.success('批量删成功')
    init()
  })
}
//选择
const xuan = (val: any) => {
  // console.log(val, '1111')
  let ids = val.map((item: any, index: number) => {
    return item.id
  })
  // console.log(ids)
  deldata.value = ids
  console.log([...deldata.value]) //ref的形式得到其实本质上是这个可以打印看看
}
//option学院
const options = [
  {
    value: 0,
    label: '请选择'
  },
  {
    value: 2,
    label: '网站工程学院'
  },
  {
    value: 1,
    label: '游戏学院'
  }
]
//option市场部
const options1 = [
  {
    value: 0,
    label: '请选择'
  },
  {
    value: '招生办',
    label: '招生办'
  },
  {
    value: '晋中市场部',
    label: '晋中市场部'
  },
  {
    value: '中原市场部',
    label: '中原市场部'
  },
  {
    value: '辽宁市场部',
    label: '辽宁市场部'
  }
]
//城市
const optionscity = CityData.map((item, index) => {
  let props = {
    value: item.code,
    label: item.label
  }
  if (item.children) {
    props.children = item.children.map((v, i) => ({
      value: v.code,
      label: v.label,
      children: v.children
        ? v.children.map((chid) => ({
            value: chid.code,
            label: chid.label
          }))
        : []
    }))
  }
  return props
})
// const optionscity = CityData.map((item, index) => {
//   let props = { ...item }
//   props.value = item.code
//   props.label = item.label
//   if (item.children) {
//     props.children = item.children.map((v, i) => {
//       return {
//         value: v.code,
//         label: v.label
//       }
//     })
//   }
//   return props
// })
//城市数据
// console.log(CityData, optionscity, '11111')
//城市码
const handleChange = (value: Object) => {
  console.log(value)
}
//列表数据
const init = (page = 1, limit = 10) => {
  getlist({ limit, skip: (page - 1) * limit }).then((res) => {
    totalItems.value = res.data.data.total
    console.log(res, '111')
    tableData.value = res.data.data.result.map((item: any, index: number) => {
      if (item.status == '1') {
        item.status = '未毕业'
      } else if (item.status === '2') {
        item.status = '返校重听'
      } else if (item.status === '3') {
        item.status = '已就业'
      } else if (item.status == '4') {
        item.status = '返回未就业'
      } else if (item.status == '5') {
        item.status = '以往未就业'
      }
      return item
    })
    // senToparent(tableData.value.slice(0, 6))
  })
}
//页面加载
onMounted(() => {
  init(currentPage.value, pageSize.value)
})
////切换分页
const handlePageChange = (page: number) => {
  currentPage.value = page
  init(page, pageSize.value)
}
//接口搜索
const sousuo = () => {
  searchDate.workCity = lastWorkCityValue.value
  searchDate.page = currentPage.value // 确保搜索时使用当前页码
  searchDate.limit = pageSize.value

  if (searchDate.workCity === '3') {
    delete searchDate.workCity
  } else {
    // 移除其他空值参数
    for (let key in searchDate) {
      if (!searchDate[key] && key !== 'page' && key !== 'limit') {
        delete searchDate[key]
      }
    }
  }
  // console.log(searchDate)
  getlist(searchDate).then((res) => {
    console.log(res, '接口搜索')
    totalItems.value = res.data.data.total
    tableData.value = res.data.data.result.map((item: any, index: number) => {
      if (item.status == '1') {
        item.status = '未毕业'
      } else if (item.status === '2') {
        item.status = '返校重听'
      } else if (item.status === '3') {
        item.status = '已就业'
      } else if (item.status == '4') {
        item.status = '返回未就业'
      } else if (item.status == '5') {
        item.status = '以往未就业'
      }
      return item
    })
  })
}
//编辑按钮
const handleEdit = (index: number, row: any) => {
  // console.log(row)
  dialogFormVisible.value = true
  flag.value = false
  form.id = row.id
  form.stuNo = row.stuNo
  form.stuName = row.stuName
  form.className = row.className
  form.workCity = row.workCity
  switch (row.status) {
    case '未毕业':
      form.status = '1'
      break
    case '返校重听':
      form.status = '2'
      break
    case '已就业':
      form.status = '3'
      break
    case '返回未就业':
      form.status = '4'
      break
    case '以往未就业':
      form.status = '5'
      break

    default:
      break
  }
  form.origin = row.origin
  switch (row.collegeName) {
    case '网站工程学院':
      form.collegeid = '2'
      break
    case '游戏学院':
      form.collegeid = '1'
      break

    default:
      break
  }
}
//删除确认框
const confirmEvent = (index: number, row: any) => {
  // console.log(index, row)
  let id = row.id
  // console.log(id)

  dellist(id)
    .then((res) => {
      console.log(res, '删除信息')
      if (res.data.code == 200) {
        ElMessage.success('删除成功')
        init()
      }
    })
    .catch((err) => {
      console.log('删除错误信息', err)
    })
}
const cancelEvent = () => {
  ElMessage.error('删除失败')
}
//添加
const add = () => {
  dialogFormVisible.value = true
  flag.value = true
  form.stuNo = ''
  form.stuName = ''
  form.className = ''
  form.status = ''
  form.origin = ''
  form.collegeid = ''
  form.workCity = ''
}
//提交
const submit = () => {
  console.log(form)
  const { stuNo, className, stuName, status, origin, collegeid, workCity } = form
  if (flag.value) {
    addlist({ stuNo, className, stuName, status, origin, collegeid, workCity })
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage.success('新增成功')
          init()
        }
        // console.log(res, '新增数据')
      })
      .catch((err) => {
        console.log('新增错误信息', err)
      })
  } else {
    edilist(form)
      .then((res) => {
        if (res.data.code == 200) {
          ElMessage.success('编辑成功')
          init()
        }
        // console.log(res, '编辑信息')
      })
      .catch((err) => {
        console.log('编辑错误信息', err)
      })
  }
  dialogFormVisible.value = false
}
//查看详情
const cha = (row: any) => {
  let id = row.id
  detaillist(id).then((res) => {
    // console.log(res, '查看信息')
    dialogFormVisible1.value = true
    chadata.value = res.data.data
  })
}
//取消
const cancel = () => {
  dialogFormVisible.value = false
}
//导出
const handleExport = () => {
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = 'http://localhost:3002/v1.0/api/export/students?' + qs.stringify(searchDate)
  link.setAttribute('download', '学生信息表.xls')
  document.documentElement.appendChild(link)
  link.click()
}
//导入表格
const showCode = ref(false)
const handlestudent = (file) => {
  console.log(file.file)
  let formDate = new FormData()
  formDate.append('excelFile', file.file)
  formDate.append('code', '1100')
  studenimport(formDate).then((res) => {
    console.log(res, '导入信息')
    if (res.data.code == 200) {
      ElMessage.success('导入成功')
      showCode.value = true
      dialogTableVisible.value = false
      init()
    } else {
      ElMessage.error('导入失败')
    }
  })
}
const confirm = () => {
  if (showCode.value == false) {
    ElMessage.error('导入失败')
  } else {
    dialogTableVisible.value = false
  }
}
</script>

<style scoped lang="scss">
.bei {
  width: 100%;
  height: 100%;
  background: #f0f2f5;
  padding-top: 20px;
}
.top {
  width: 100%;
  height: 100px;
  border-bottom: 1px solid #ccc;
  background: #fff;
  .inpx {
    width: 80%;
    height: 40px;
    display: flex;
    align-items: center;
    div {
      width: 30%;
    }
  }
  .btn {
    display: flex;
    align-items: center;
    height: 50px;
  }
}
.table {
  margin: 10px;
}
.inp {
  width: 200px;
  height: 30px;
}
.fenye {
  float: right;
  height: 50px;
  margin-top: 20px;
}
</style>